package finalproject.mobapp.ARPackage;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import finalproject.mobapp.HttpRequestController.CustomHttpClient;

import android.location.Location;
import android.location.LocationManager;

public class PoiRetrieval {
	public static HashMap<Integer, Poi> GetNearbyPois(String category, int radius, Location userLocation) {
		HashMap<Integer, Poi> result = new HashMap<Integer, Poi>();
		
		Double userlatitude = userLocation.getLatitude();
		Double userlongitude = userLocation.getLongitude();
		
		//build request
    	ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("category", category));
        postParameters.add(new BasicNameValuePair("distance", String.valueOf(radius)));
        postParameters.add(new BasicNameValuePair("latitude", String.valueOf(userlatitude)));
        postParameters.add(new BasicNameValuePair("longitude", String.valueOf(userlongitude)));
        
        //get response
        String response = null;
        try {
			response = CustomHttpClient.executeHttpPost(CustomHttpClient.BASE_URL + "getNearbyPois", postParameters);
			JSONArray jArray = new JSONArray(response);
			JSONObject json_data = null;
			for (int i=0; i<jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				
				int poi_id = json_data.getInt("id");
				String poi_title = json_data.getString("title");
				String poi_description = json_data.getString("description");
				
				Double poi_latitude = json_data.getDouble("latitude");
				Double poi_longitude = json_data.getDouble("longitude");
				Location poi_location = new Location(LocationManager.NETWORK_PROVIDER);
				poi_location.setLatitude(poi_latitude);
				poi_location.setLongitude(poi_longitude);
				
				float poi_distance = (float)json_data.getDouble("distance");
				
				ArrayList<ARObject> objects = new ArrayList<ARObject>();
				JSONArray objects_array = json_data.getJSONArray("objects");
				JSONObject object_data = null;
				for (int j=0; j<objects_array.length(); j++) {
					object_data = objects_array.getJSONObject(j);
					
					int object_id = object_data.getInt("object_id");
					String object_path = object_data.getString("object_path");
					int object_type = object_data.getInt("object_type");
					
					ARObject object = new ARObject(object_id, object_path, object_type);
					objects.add(object);
				}
				
				Poi poi = new Poi(poi_id, poi_title, poi_description, poi_location, poi_distance, objects);
				
				result.put(poi_id, poi);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
}
